# 创建规格管理页面
<template>
  <div class="spec-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>规格管理</span>
          <el-button type="primary" @click="handleAdd">添加规格</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable @change="handleSearch">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 规格列表 -->
      <el-table
        v-loading="loading"
        :data="categorySpecs"
        style="width: 100%"
      >
        <el-table-column prop="name" label="规格名称" min-width="120" />
        <el-table-column prop="categoryName" label="所属分类" min-width="120" />
        <el-table-column label="规格类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isGlobal ? 'success' : 'primary'">
              {{ row.isGlobal ? '全局规格' : '自定义规格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="规格值" min-width="200">
          <template #default="{ row }">
            <el-tag
              v-for="value in row.values"
              :key="value"
              class="spec-value-tag"
              :type="row.isGlobal ? 'success' : ''"
            >
              {{ value }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group v-if="!row.isGlobal">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </el-button-group>
            <el-button
              v-else
              type="primary"
              link
              @click="handleViewDetail(row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 添加/编辑规格对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加自定义规格' : dialogType === 'edit' ? '编辑规格' : '规格详情'"
        width="500px"
        destroy-on-close
      >
        <el-form
          ref="specFormRef"
          :model="specForm"
          :rules="specRules"
          label-width="100px"
          :disabled="dialogType === 'view'"
        >
          <el-form-item label="规格名称" prop="name">
            <el-input v-model="specForm.name" placeholder="请输入规格名称" />
          </el-form-item>

          <el-form-item label="所属分类" prop="categoryId" v-if="!specForm.isGlobal">
            <el-select v-model="specForm.categoryId" placeholder="请选择分类">
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="排序" prop="sort">
            <el-input-number 
              v-model="specForm.sort" 
              :min="1" 
              :step="1"
              controls-position="right"
            />
          </el-form-item>

          <el-form-item label="规格值" prop="values">
            <div class="spec-values">
              <el-tag
                v-for="(value, index) in specForm.values"
                :key="index"
                :closable="dialogType !== 'view'"
                class="spec-value-tag"
                :type="specForm.isGlobal ? 'success' : ''"
                @close="removeValue(index)"
              >
                {{ value }}
              </el-tag>
            </div>
            <div class="spec-value-input" v-if="dialogType !== 'view'">
              <el-input
                v-model="inputValue"
                placeholder="输入规格值后回车"
                @keyup.enter.prevent="addValue"
                @blur="$refs.specFormRef?.validateField('values')"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">{{ dialogType === 'view' ? '关闭' : '取消' }}</el-button>
            <el-button v-if="dialogType !== 'view'" type="primary" @click="submitSpec">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryTree } from '@/api/category'
import { 
  getMerchantSpecTemplates,
  getGlobalSpecTemplates,
  getMerchantSpecDetail,
  getGlobalSpecDetail,
  createSpec,
  updateSpec,
  deleteSpec
} from '@/api/product'

// 状态定义
const loading = ref(false)
const categorySpecs = ref([])
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const inputValue = ref('')

// 搜索表单
const searchForm = ref({
  categoryId: ''
})

// 规格表单
const specFormRef = ref(null)
const specForm = ref({
  id: null,
  name: '',
  categoryId: '',
  values: [],
  sort: 1,
  isGlobal: false
})

// 表单校验规则
const specRules = {
  name: [
    { required: true, message: '请输入规格名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  values: [
    { required: true, message: '请添加至少一个规格值', trigger: ['change', 'blur'] }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', message: '排序值必须为数字', trigger: 'blur' }
  ]
}

// 获取规格列表
const fetchSpecs = async () => {
  try {
    loading.value = true
    
    // 并行请求商家规格和全局规格
    const [merchantRes, globalRes] = await Promise.all([
      getMerchantSpecTemplates(searchForm.value.categoryId),
      getGlobalSpecTemplates()
    ])

    // 处理商家规格
    const merchantSpecs = merchantRes.code === 200 ? merchantRes.data : []
    
    // 处理全局规格
    const globalSpecs = globalRes.code === 200 ? globalRes.data : []
    
    // 合并并处理规格数据
    const allSpecs = [
      ...globalSpecs.map(spec => ({
        ...spec,
        categoryName: '全局规格',
        isGlobal: true
      })),
      ...merchantSpecs.map(spec => ({
        ...spec,
        categoryName: spec.categoryId ? categories.value.find(c => c.id === spec.categoryId)?.name || '未分类' : '全部分类',
        isGlobal: false
      }))
    ]
    
    categorySpecs.value = allSpecs
    total.value = allSpecs.length

    if (allSpecs.length === 0) {
      ElMessage.warning('暂无规格数据')
    }
  } catch (error) {
    console.error('获取规格列表失败:', error)
    ElMessage.error('获取规格列表失败')
    categorySpecs.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryTree()
    if (res.code === 200) {
      categories.value = flattenCategoryTree(res.data)
    } else {
      categories.value = []
      ElMessage.warning(res.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 将分类树扁平化为列表
const flattenCategoryTree = (tree) => {
  const result = []
  const flatten = (items, parentName = '') => {
    items.forEach(item => {
      const fullName = parentName ? `${parentName} / ${item.name}` : item.name
      result.push({
        id: item.id,
        name: fullName
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, fullName)
      }
    })
  }
  flatten(tree)
  return result
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchSpecs()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    categoryId: ''
  }
  currentPage.value = 1
  fetchSpecs()
}

// 添加规格
const handleAdd = () => {
  dialogType.value = 'add'
  specForm.value = {
    id: null,
    name: '',
    categoryId: '',
    values: [],
    sort: 1,
    isGlobal: false
  }
  dialogVisible.value = true
}

// 编辑规格
const handleEdit = async (row) => {
  try {
    const res = await getMerchantSpecDetail(row.id)
    if (res.code === 200 && res.data) {
      specForm.value = {
        id: res.data.id,
        name: res.data.name,
        categoryId: res.data.categoryId,
        values: res.data.values || [],
        sort: res.data.sort || 0
      }
      dialogVisible.value = true
      dialogType.value = 'edit'
    }
  } catch (error) {
    console.error('获取规格详情失败:', error)
    ElMessage.error('获取规格详情失败')
  }
}

// 删除规格
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该规格吗？删除后不可恢复！', '警告', {
      type: 'warning'
    })
    
    const res = await deleteSpec(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchSpecs()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规格失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 添加规格值
const addValue = () => {
  const value = inputValue.value.trim()
  if (value) {
    // 检查是否已存在该规格值
    if (!specForm.value.values.includes(value)) {
      // 使用数组方式添加规格值
      specForm.value.values = [...specForm.value.values, value]
      inputValue.value = ''
      // 手动触发验证
      specFormRef.value?.validateField('values')
    } else {
      ElMessage.warning('该规格值已存在')
    }
  }
}

// 移除规格值
const removeValue = (index) => {
  // 使用数组过滤方式移除规格值
  specForm.value.values = specForm.value.values.filter((_, i) => i !== index)
  // 手动触发验证
  specFormRef.value?.validateField('values')
}

// 提交规格
const submitSpec = async () => {
  if (!specFormRef.value) return
  
  try {
    await specFormRef.value.validate()
    
    if (specForm.value.values.length === 0) {
      ElMessage.warning('请至少添加一个规格值')
      return
    }

    const submitData = {
      name: specForm.value.name,
      categoryId: specForm.value.categoryId,
      values: specForm.value.values,
      sort: specForm.value.sort
    }

    let res
    if (dialogType.value === 'add') {
      res = await createSpec(submitData)
    } else {
      res = await updateSpec(specForm.value.id, submitData)
    }

    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      fetchSpecs()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('提交规格失败:', error)
    ElMessage.error('提交失败')
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchSpecs()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchSpecs()
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 查看规格详情
const handleViewDetail = async (row) => {
  try {
    const res = row.isGlobal 
      ? await getGlobalSpecDetail(row.id)
      : await getMerchantSpecDetail(row.id)

    if (res.code === 200) {
      dialogType.value = 'view'
      specForm.value = {
        id: res.data.id,
        name: res.data.name,
        categoryId: res.data.categoryId,
        values: [...res.data.values],
        sort: res.data.sort,
        isGlobal: res.data.isGlobal
      }
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取规格详情失败')
    }
  } catch (error) {
    console.error('获取规格详情失败:', error)
    ElMessage.error('获取规格详情失败')
  }
}

onMounted(() => {
  fetchCategories()
  fetchSpecs()
})
</script>

<style scoped>
.spec-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.spec-value-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.spec-value-input {
  margin-top: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 